package pl.edu.pjwstk.kor.database.init;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

import pl.edu.pjwstk.kor.model.Person;

abstract class PersonInitalizer<T extends Person> extends AbstractDataInitalizer<T> {
	protected List<String> femaleFirstNames;
	protected List<String> femaleLastNames;
	protected List<String> maleFirstNames;
	protected List<String> maleLastNames;
	
	private final Class<T> clazz;
	
	public PersonInitalizer(Class<T> clazz) {
		this.clazz = clazz;
		try {
			femaleFirstNames = readNames(new File("src/main/resources/names_female.csv"));
			femaleLastNames = readNames(new File("src/main/resources/lastNames_female.csv"));
			
			maleFirstNames = readNames(new File("src/main/resources/names_male.csv"));
			maleLastNames = readNames(new File("src/main/resources/lastNames_male.csv"));	
		} catch (IOException e) {
			throw new IllegalStateException("Can not initalize data", e);
		}
	}
	
	protected T createRandomPerson() {
		try {
			T result = clazz.newInstance();
			
			if(random.nextBoolean()) {
				result.setFirstName(selectRandom(maleFirstNames, random));
				result.setLastName(selectRandom(maleLastNames, random));
			} else {
				result.setFirstName(selectRandom(femaleFirstNames, random));
				result.setLastName(selectRandom(femaleLastNames, random));
			}
			
			return result;
		} catch (Exception e) {
			throw new IllegalStateException("Can not create person", e);
		}
	}
	
	private List<String> readNames(File file) throws IOException {
		List<String> result = new ArrayList<String>();
		for(String line : FileUtils.readLines(file, "UTF8")) {
			String lastPart = line.substring(1);
			String firstLetter = line.charAt(0) + "";
			result.add(firstLetter.toUpperCase() + lastPart.trim());
		}
		return result;
	}
}
